package com.qiyu.bigdata.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Map;

public class HttpUtil {
    /**
     * form表单数据请求
     * @param url URL
     * @param formData 表单数据
     * @return JSONObject
     */
    public static JSONObject doPostByForm(String url, Map<String,Object> formData) {
        RestTemplate template = new RestTemplate();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        for(Map.Entry<String, Object> m : formData.entrySet()){
            map.add(m.getKey(), m.getValue());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
        //        System.out.println(jsonObject);
        return template.execute(url, HttpMethod.POST, template.httpEntityCallback(entity), response -> {
            InputStream stream = response.getBody();
            byte[] bytes = FileCopyUtils.copyToByteArray(stream);
            return JSON.parseObject(bytes);
        });
    }


    public static JSONObject doPost(String url) throws URISyntaxException, IOException {
//        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//        ClientHttpRequest request = factory.createRequest(new URI(url), HttpMethod.POST);
//        ClientHttpResponse httpResponse = request.execute();
//        InputStream stream = httpResponse.getBody();
//        byte[] bytes = FileCopyUtils.copyToByteArray(stream);
//        JSONObject jsonObject = JSON.parseObject(bytes);
//        System.out.println(jsonObject);
//        return jsonObject;
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(headers);
        return template.execute(url, HttpMethod.POST, template.httpEntityCallback(entity), response -> {
            InputStream stream = response.getBody();
            byte[] bytes = FileCopyUtils.copyToByteArray(stream);
            return JSON.parseObject(bytes);
        });
    }

}
